package cn.ygh.bbo.system.service.impl;

import cn.ygh.bbo.system.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.ygh.bbo.framerwork.core.Grid;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.common.annotation.DataScope;
import cn.ygh.bbo.system.bean.Dept;
import cn.ygh.bbo.system.mapper.DeptMapper;
import cn.ygh.bbo.system.service.DeptService;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：部门  ServiceImpl
 * @author ygh
 */
@Service
public class DeptServiceImpl implements DeptService{

    private final Logger logger=LoggerFactory.getLogger(getClass());

    @Autowired
    DeptMapper mapper;

    @Autowired
    AdminService adminService;

    /**
    * 保存对象
    * @param  dept 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(Dept dept) {
        //保存之前通用处理
        beforeCreate(dept);
        dept.def();
        return mapper.insert(dept);
    }

    /**
    * 更新对象
    * @param  dept 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Dept dept) {
        if(dept.getId()==null){
            throw new TipException("id can not null");
        }
        //更新之前通用处理
        beforeUpdate(dept);
        dept.def();
        return mapper.updateById(dept);
    }

    /**
    * 批量更新
    * @param  dept 对象信息
    * @param ids
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBatchByIds(Dept dept, Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.updateBatchByIds(dept,ids);
    }

    /**
    * 根据ID删除对象
    * @param id
    * @return
    */
    @Override
    public int deleteById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        if(checkLink(id)){
            return mapper.deleteById(id);
        }
        return 0;
    }

    /**
    * 删除关联判断
    * @param id
    */
    private boolean checkLink(Serializable id) {
        Integer i=Integer.valueOf(id.toString());
        long count=adminService.getCountByDeptId(i);
        if (count>0){
            throw new TipException(String.format("管理员相关还存在%s条数据,无法删除",count));
        }
        count=getCountByParentId(i);
        if (count>0){
            throw new TipException(String.format("下属部门还存在%s条数据,无法删除",count));
        }
        return true;
    }

    /**
    * 根据ID数组批量删除对象
    * @param ids
    * @return
    */
    @Override
    public int deleteByIds(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        int result=0;
        for (Serializable id:ids){
            result+=deleteById(id);
        }
        return result;
    }

    /**
    * 根据ID获取对象
    * @param id
    * @return
    */
    @Override
    public Dept getById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        return mapper.selectById(id);
    }

    /**
    * 根据ID数组获取对象列表
    * @param ids
    * @return
    */
    @Override
    public List<Dept> listfindByIn(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.selectBatchIds(Arrays.asList(ids));
    }

    /**
    * 根据对象信息获取满足条件的对象列表
    * @param  dept 对象信息
    * @param pageable 分页条件为空则不分页
    * @return
    */
    @DataScope
    @Override
    public List<Dept> listfind(Dept dept, Pageable pageable) {
        if (pageable!=null && pageable.getPageNumber()!=0){
            PageHelper.startPage(pageable.getPageNumber()
                    , pageable.getPageSize(), false);
        }
        return mapper.selectByObj(dept);
    }

    /**
     * 获取所有下属部门
     *
     * @param parentId
     * @return
     */
    @Override
    public List<Dept> listfindByParentId(Integer parentId) {
        if (parentId==null || new Integer(0).equals(parentId)){
            return new ArrayList<>();
        }
        //获取所有的部门
        List<Dept>depts=listfind(new Dept(), null);
        List<Dept>result=new ArrayList<>();
        List<Integer>parants=new ArrayList<>();
        parants.add(parentId);
        while (true){
            if (parants.size()==0){
                break;
            }
            List<Dept>children=depts.stream()
                    .filter(e->parants.contains(e.getParentId())).collect(Collectors.toList());
            parants.clear();
            for (Dept dept:children){
                //防止循环调用
                Dept d=result.stream().filter(e->e.getId()
                        .equals(dept.getId())).findFirst().orElse(null);
                if (d==null){
                    result.add(dept);
                    parants.add(dept.getId());
                }
            }
        }
        return result;
    }

    /**
    * 根据对象信息获取满足条件的对象列表和总数
    * @param  dept 对象信息
    * @param pageable 分页条件
    * @return
    */
    @DataScope
    @Override
    public Grid listGrid(Dept dept, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber()
                , pageable.getPageSize(), true);
        List<Dept> depts = mapper.selectByObj(dept);
        PageInfo<Dept>pageInfo=new PageInfo<>(depts);
        Grid grid=new Grid();
        grid.setTotal((int) pageInfo.getTotal());
        grid.setRows(pageInfo.getList());
        return grid;
    }

    /**
     * 获得子部门数量
     *
     * @param parentId
     * @return
     */
    @Override
    public long getCountByParentId(Integer parentId) {
        Dept params=new Dept();
        params.setParentId(parentId);
        return mapper.selectCountByObj(params);
    }
}
